const path = require('path');
const fs = require('fs');
const ora = require('ora');
const co = require('co');
const prompt = require('co-prompt');
const chalk = require('chalk');
const templates = require("../templates");
const util = require('./util.js')
const temps = {};// {0:seeai-template}
const temps2 = {};//{name:seeai-template,path:https://gitee.com/xccjh/seeai-template.git}
const sourcePath = path.resolve(__dirname, '../download');

function getTemps(templates) {
    for (let key in templates.list) {
        let item = templates.list[key]
        temps[key] = item.name;
        temps2[item.name] = item.path;
    }
    ;
}

const generator = function* (name) {
    let tempName = name;
    let path = temps2[name];
    if (!Object.keys(name).length) {
        console.log('    可用模板列表:')
        for (let key in temps) {
            let tempName = temps[key]
            console.log(
                '    ' + chalk.green(key) +
                ' : ' + chalk.green(tempName))
        }
        tempName = yield prompt("    请选择模板类型(0): ")
        if (!tempName) {
            tempName = 0
        }
        path = temps2[temps[tempName]];
    }
    if (temps[tempName] || temps2[tempName]) {
        console.log('    ----------------------------------------')
        let projectName = yield prompt("    请输入项目名称(demo):")
        if (!projectName) {
            projectName = "demo"
        }
        console.log('    ----------------------------------------')
        downloadTemplates(path, projectName);

    } else {
        console.log(chalk.red(`   模版[${tempName}]不存在`))
        process.exit(0);
    }
}

function downloadTemplates(path, projectName) {
    let spanner = ora("  正在初始化项目，请稍等......");
    spanner.start();
    if (fs.existsSync(sourcePath)) {
        //刪除原文件
        util.rmdirSync(sourcePath);
    }
    require("child_process").exec(`git clone ${path} ${sourcePath}`, function (err, stdout, stderr) {
        if (err) {
            spanner.stop();
            console.log('   ', chalk('项目构建失败'), err);
            process.exit(0);
        }
        startBuildProject(spanner, projectName)
    })
}

function startBuildProject(spanner, projectName) {
    const targetPath = path.resolve(process.cwd(), projectName)
    if (fs.existsSync(targetPath)) {
        //目标文件夹存在，刪除
        util.rmdirSync(targetPath);
    }
    util.copyDirSync(sourcePath, targetPath)
    console.log('                                               ')
    console.log('   ', chalk.green('*'), chalk.green('项目构建成功'));
    console.log('   ', chalk.green(`cd ${projectName} && yarn && yarn start`));
    spanner.stop();
    process.exit(0);
}

module.exports = function (name) {
    getTemps(templates);
    co(generator(name));
}

